import axios from 'axios';

// 创建axios实例
const apiClient = axios.create({
  timeout: 150000, // 增加超时时间以支持深度思考模式（150秒）
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 避免在登录页面重复跳转
    const isLoginPage = window.location.pathname === '/login';
    
    if (error.response?.status === 401 && !isLoginPage) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    
    // 记录错误信息用于调试
    console.error('聊天API请求错误:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      message: error.message,
      data: error.response?.data
    });
    
    return Promise.reject(error);
  }
);

const chatService = {
  // 发送聊天消息
  async sendMessage(message, sessionId = null, enableSearch = false, searchEngine = 'tavily', enablePersonalization = false, enableDeepThinking = false) {
    try {
      // 参数验证
      if (!message || !message.trim()) {
        return {
          success: false,
          message: '消息内容不能为空',
        };
      }

      const response = await apiClient.post('/api/v1/chat/message', {
        message: message.trim(),
        session_id: sessionId,
        enable_search: enableSearch,
        search_engine: searchEngine,
        enable_personalization: enablePersonalization,
        enable_deep_thinking: enableDeepThinking,
      });
      
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('发送消息失败:', error);
      
      let errorMessage = '发送消息失败';
      
      try {
        if (error.code === 'ECONNABORTED') {
          errorMessage = enableDeepThinking ? 
            '深度思考模式处理时间较长，请求超时。请稍后重试或关闭深度思考模式' : 
            '请求超时，AI正在思考中，请稍后重试';
        } else if (error.code === 'NETWORK_ERROR' || error.message === 'Network Error') {
          errorMessage = '网络连接失败';
        } else if (error.response) {
          const status = error.response.status;
          const data = error.response.data;
          
          if (status === 401) {
            errorMessage = '请先登录';
          } else if (status === 422) {
            errorMessage = data?.detail || '消息格式错误';
          } else if (status === 429) {
            errorMessage = '请求过于频繁，请稍后再试';
          } else if (status >= 500) {
            errorMessage = 'AI服务暂时不可用，请稍后重试';
          } else {
            errorMessage = data?.detail || data?.message || `请求失败 (${status})`;
          }
        } else if (error.request) {
          errorMessage = 'AI服务无响应，请检查网络连接';
        }
      } catch (parseError) {
        console.error('解析错误信息时出错:', parseError);
        errorMessage = '发送消息失败，请稍后重试';
      }
      
      return {
        success: false,
        message: errorMessage,
      };
    }
  },

  // 获取聊天历史
  async getChatHistory(sessionId = null) {
    try {
      const params = sessionId ? { session_id: sessionId } : {};
      const response = await apiClient.get('/api/v1/chat/history', { params });
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('获取聊天历史失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '获取聊天历史失败',
      };
    }
  },

  // 清空聊天历史
  async clearChatHistory(sessionId = null) {
    try {
      const params = sessionId ? { session_id: sessionId } : {};
      const response = await apiClient.delete('/api/v1/chat/history', { params });
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('清空聊天历史失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '清空聊天历史失败',
      };
    }
  },

  // 获取聊天服务状态
  async getChatStatus() {
    try {
      const response = await apiClient.get('/api/v1/chat/status');
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('获取聊天状态失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '获取聊天状态失败',
      };
    }
  },

  // 会话管理API
  // 获取用户会话列表
  async getSessions() {
    try {
      const response = await apiClient.get('/api/v1/chat/sessions');
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('获取会话列表失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '获取会话列表失败',
      };
    }
  },

  // 创建新会话
  async createSession(sessionTitle = null) {
    try {
      const response = await apiClient.post('/api/v1/chat/sessions', {
        session_title: sessionTitle,
      });
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('创建会话失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '创建会话失败',
      };
    }
  },

  // 重命名会话
  async renameSession(sessionId, newTitle) {
    try {
      const response = await apiClient.put(`/api/v1/chat/sessions/${sessionId}`, {
        new_title: newTitle,
      });
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('重命名会话失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '重命名会话失败',
      };
    }
  },

  // 删除会话
  async deleteSession(sessionId) {
    try {
      const response = await apiClient.delete(`/api/v1/chat/sessions/${sessionId}`);
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('删除会话失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '删除会话失败',
      };
    }
  },

  // 获取会话信息
  async getSessionInfo(sessionId) {
    try {
      const response = await apiClient.get(`/api/v1/chat/sessions/${sessionId}`);
      return {
        success: true,
        data: response.data,
      };
    } catch (error) {
      console.error('获取会话信息失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '获取会话信息失败',
      };
    }
  },
};

export default chatService;